package org.king.controller.auth;

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import org.king.MainApplication;
import org.king.entity.User;
import org.king.service.UserService;
import org.king.util.AlertUtil;
import org.king.util.StringUtil;
import org.springframework.stereotype.Controller;

@Controller
public class RegisterController {

    private final UserService userService;
    // 通过构造函数注入（推荐）
    public RegisterController(UserService userService) {
        this.userService = userService;
    }

    @FXML
    private TextField reg_account;
    @FXML
    private PasswordField reg_password;
    @FXML
    private PasswordField reg_confirm;
    @FXML
    private Button register;
    @FXML
    private TextField reg_email;
    @FXML
    private void doRegister() {
        String account = reg_account.getText();
        String password = reg_password.getText();
        String confirm = reg_confirm.getText();
        String email = reg_email.getText();
        if (StringUtil.isEmpty(account) || StringUtil.isEmpty(password) || StringUtil.isEmpty(confirm)) {
            AlertUtil.showAlert(Alert.AlertType.ERROR,"注册失败","账号，密码，确认密码不能为空","请重新输入");
        }
        else if (account.length() != 10){
            AlertUtil.showAlert(Alert.AlertType.ERROR,"注册失败","账户学号长度为10","请重新输入");
            reg_account.clear();
        }
        else if (!password.equals(confirm)){
            AlertUtil.showAlert(Alert.AlertType.ERROR,"注册失败","密码输入不一致","请重新注册");
            reg_password.clear();
            reg_confirm.clear();
        }
        else if (userService.getUserByAccount(account)!=null){
            AlertUtil.showAlert(Alert.AlertType.ERROR, "注册失败", "账号已经存在", "请使用其他账号或登录");
        }
        else {
            User user = new User(0,account,password,email,"user");
            int flag = userService.addUser(user);
            if (flag == 0) {
                AlertUtil.showAlert(Alert.AlertType.ERROR, "注册失败", "用户创建失败", "请重试");
            }
            MainApplication.changeView("/view/auth/login-view.fxml");
        }
    }
    @FXML
    private void cancel() {
        MainApplication.changeView("/view/auth/login-view.fxml");
    }
}
